package com.wxs.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wxs.common.bean.UserLoginInfoBean;
import com.wxs.common.pojo.Resource;
import com.wxs.common.pojo.Role;
import com.wxs.common.pojo.User;
import com.wxs.common.service.LoginService;
import com.wxs.common.service.ResourceService;
import com.wxs.common.service.RoleService;
import com.wxs.common.service.UserService;
import com.wxs.common.utils.JsonResult;
import com.wxs.common.utils.StringUtil;

/**
 * 登录
 * 
 * @author admin
 *
 */
@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private UserService userService;

	@Autowired
	private ResourceService resourceService;
	@Autowired
	private RoleService roleService;

	@Override
	public JsonResult login(String uname, String passwrod, String vcode, boolean saveLogin) {
		String passwrod_m = StringUtil.md5(passwrod);
		JsonResult jsonResult = new JsonResult();
		User user = userService.selectByName(uname);
		if (user == null) {
			jsonResult.setState(1);
			jsonResult.setMessage("用户不存在！");
			return jsonResult;
		}

		if (!user.getPassword().equals(passwrod_m)) {
			jsonResult.setState(1);
			jsonResult.setMessage("用户名或密码错误！");
			return jsonResult;
		}

		UserLoginInfoBean userLoginInfoBean = new UserLoginInfoBean();
		List<Resource> resources = resourceService.queryForList(user.getRolegroupid());
		List<Resource> topResourceList = new ArrayList<Resource>();
		for (Resource resource : resources) {
			if (resource.getPid().equals(0)) {
				List<Resource> children = getChildren(resources, resource.getId());
				resource.setChildren(children);
				topResourceList.add(resource);
			}
			userLoginInfoBean.getResMap().put(resource.getName(), resource);
		}
		userLoginInfoBean.setResList(topResourceList);

		List<Role> roles = roleService.queryForList(user.getRolegroupid());
		for (Role role : roles) {
			userLoginInfoBean.getRoleMap().put(role.getName(), role);
		}

		userLoginInfoBean.setUser(user);
		userLoginInfoBean.setRoleList(roles);
		jsonResult.setState(0);
		jsonResult.setMessage("登录成功！");
		jsonResult.setData(userLoginInfoBean);
		return jsonResult;
	}

	private List<Resource> getChildren(List<Resource> resourceList, Integer parentid) {
		List<Resource> children = new ArrayList<Resource>();
		for (Resource resource : resourceList) {
			if (resource.getPid().compareTo(parentid) == 0) {
				resource.setChildren(this.getChildren(resourceList, resource.getId()));
				children.add(resource);
			}
		}
		return children;
	}

}
